#include "groupmore.h"
#include "ui_groupmore.h"
#include "widget.h"

#include <QAction>
#include <QThread>
#include <QMenu>

QDataStream& operator>>(QDataStream& stream, group_memb& member) {
    stream >> member.membname >> member.job >> member.status >> member.img;
    return stream;
}

GroupMore::GroupMore(QString groupname, QString username, QTcpSocket *s, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GroupMore)
{
    ui->setupUi(this);
    _groupname = groupname;
    _username = username;
    _socket = s;

    // 1. 向数据库请求群成员数据，展示在list中
    QDataStream stream(_socket);
    QList<group_memb> members; // 存储group_memb结构体的列表
    QString action = "GROUP_MEB_LIST";
    stream << action << _groupname;
//    stream << _groupname;

    if (_socket->waitForReadyRead()) {
        bool response;
        stream >> response;
        if (response) {
            qDebug() << "row 26 response is " << response;
            _members.clear();
            stream >> members;
            qDebug() << "row 36 get members";
            /*******
            while(1) {
                QString membname;
                QString job;
                QByteArray img;
                QString status;

                stream >> membname;
                if (membname == "DONE") {
                    qDebug() << "row 27 membname is " << membname;
                    break;
                }
                stream >> img >> job >> status;
//                stream >> img;
                qDebug() << "row 29 membname is " << membname << job << status;
                qDebug() << "row 31 get img, size is " << img.size();

                // 向list添加元素
                QWidget * memWidget = new QWidget();
                memWidget->setFixedHeight(60);

                //创建 UI 元素，例如头像、用户名等
                QLabel *avatarLabel = new QLabel(memWidget);
                avatarLabel->setPixmap(QPixmap::fromImage(QImage::fromData((img)).scaled(40,40, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
                QLabel *namelabel = new QLabel(membname, memWidget);
                namelabel->setObjectName("namelabel");
                QLabel *statuslabel = new QLabel(status, memWidget);
                statuslabel->setObjectName("statuslabel");


                //将 UI 元素添加到布局中
                QHBoxLayout *layout = new QHBoxLayout(memWidget);
                layout->addWidget(avatarLabel);
                layout->addWidget(namelabel);
                layout->addWidget(statuslabel);

                // 设置职位
                QLabel *ower = new QLabel(job);
                layout->addWidget(ower);

                //创建QListWidgetItem, 并设置其大小
                QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
                item->setSizeHint(QSize(350, 60 ));

                //将好友的widget设置到QListWidgetItem中
                ui->listWidget->setItemWidget(item, memWidget);

            }
            *********************************/
        }

    }

    // 遍历list
    for (QList<group_memb>::iterator it = members.begin(); it != members.end(); ++it) {
        group_memb member = *it;
        qDebug() << "Member Name: " << member.membname;
        qDebug() << "Job: " << member.job;
        qDebug() << "Status: " << member.status;
        qDebug() << "Image size: " << member.img.size();
        qDebug() << "--------row 45--------------";

        QString membname = member.membname;
        QString job = member.job;
        QByteArray img = member.img;
        QString status = member.status ;

        // 向list添加元素
        QWidget * memWidget = new QWidget();
        memWidget->setFixedHeight(60);

        //创建 UI 元素，例如头像、用户名等
        QLabel *avatarLabel = new QLabel(memWidget);
        avatarLabel->setPixmap(QPixmap::fromImage(QImage::fromData((img)).scaled(40,40, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
        QLabel *namelabel = new QLabel(membname, memWidget);
        namelabel->setObjectName("namelabel");
        QLabel *statuslabel = new QLabel(status, memWidget);
        statuslabel->setObjectName("statuslabel");

        //将 UI 元素添加到布局中
        QHBoxLayout *layout = new QHBoxLayout(memWidget);
        layout->addWidget(avatarLabel);
        layout->addWidget(namelabel);
        layout->addWidget(statuslabel);

        // 设置职位
        QLabel *ower = new QLabel(job);
        layout->addWidget(ower);
        ower->setObjectName("joblabel");

        //创建QListWidgetItem, 并设置其大小
        QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
        item->setSizeHint(QSize(350, 60 ));

        //将好友的widget设置到QListWidgetItem中
        ui->listWidget->setItemWidget(item, memWidget);

        img.clear();

    }
    // 设置样式表
    ui->listWidget->setStyleSheet(
        "QListWidget::item:hover {"
        "    background-color: #c1c9eb;"
        "}"
        "QListWidget::item:selected {"
        "    background-color: lightblue;"
        "    color: white;"
        "}"
    );

    // 2. connect群主的右击禁言、踢人
    // 设置上下文菜单策略为自定义
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);

    // 连接[群主] customContextMenuRequested 信号到槽函数
    for (const group_memb& member : members) {
        if (member.membname == _username) {
            if (member.job == "群主"){
                connect(ui->listWidget, &QListWidget::customContextMenuRequested, this, &GroupMore::onListWidgetItemClicked);
            }
        }
    }

}

GroupMore::~GroupMore()
{
    delete ui;
    _members.clear();

}


// 私有槽函数的实现
void GroupMore::onListWidgetItemClicked(QPoint pos)
{
    QListWidgetItem* selectedItem = ui->listWidget->itemAt(pos);
    if (!selectedItem)
        return;
    QListWidget* listWidget = ui->listWidget; // 假设已经存在一个 QListWidget 实例
    QWidget* itemWidget = dynamic_cast<QWidget*>(listWidget->itemWidget(selectedItem));
    QLabel* label = itemWidget->findChild<QLabel*>("namelabel");
    QString membname = label->text();
    QLabel *statuslabel = itemWidget->findChild<QLabel*>("statuslabel");
    QString status = statuslabel->text();
    QLabel *joblabel = itemWidget->findChild<QLabel*>("joblabel");
    QString job = joblabel->text();
    if (job == "群主")
        return;
    qDebug() << "row 106 label text is " << membname;

    QMenu contextMenu(this);
    QAction* muteAction = new QAction("禁言", this);
    QAction* unmuteAction = new QAction("解禁言", this);
    QAction* kickAction = new QAction("踢人", this);



    // 连接每个选项的 triggered 信号到相应的槽函数
    connect(muteAction, &QAction::triggered, this, [=]() {
        // 执行禁言操作
        //1.标签更改
        qDebug() << "禁言" << membname;
        statuslabel->setText("已禁言");

        //2.数据库修改
        QString aciton = "INHIBIT";
        QDataStream stream(_socket);
        stream << aciton;
        stream << _groupname << membname;


    });

    connect(unmuteAction, &QAction::triggered, this, [=]() {
        // 执行解禁言操作
        qDebug() << "解禁言" << membname;
        //1.标签更改
        statuslabel->setText("正常");

        //2.数据库修改
        QString aciton = "DISINHIBIT";
        QDataStream stream(_socket);
        stream << aciton;
        stream << _groupname << membname;
    });

    connect(kickAction, &QAction::triggered, this, [=]() {
        // 执行踢人操作
        qDebug() << "踢人" << membname;
        // 1.删除list该行
        delete selectedItem;

        // 2.删除数据库
        QString action = "DELETE_MEMB";
        QDataStream stream(_socket);
        stream << action;
        stream << _groupname << membname;

    });

    contextMenu.addAction(muteAction);
    contextMenu.addAction(unmuteAction);
    contextMenu.addAction(kickAction);

    // 显示菜单在鼠标右击的位置上
    contextMenu.exec(ui->listWidget->mapToGlobal(pos));
}

void GroupMore::closeEvent(QCloseEvent* event) {
    emit aboutToClose(this); // 发射信号，传递当前对象的指针
    QWidget::closeEvent(event); // 调用父类的关闭事件处理函数
}
